package com.example.cursor_orm.util;

import java.sql.*;
import java.util.Properties;
import java.io.InputStream;

/**
 * 数据库连接工具类
 * 提供数据库连接和基本操作
 */
public class DatabaseUtil {
    private static final String CONFIG_FILE = "database.properties";
    private static String url;
    private static String username;
    private static String password;
    private static String driver;
    
    static {
        loadConfig();
    }
    
    /**
     * 加载数据库配置
     */
    private static void loadConfig() {
        try {
            Properties props = new Properties();
            InputStream input = DatabaseUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE);
            if (input == null) {
                // 使用默认配置
                url = "jdbc:mysql://localhost:3306/rabc_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
                username = "root";
                password = "123456";
                driver = "com.mysql.cj.jdbc.Driver";
            } else {
                props.load(input);
                url = props.getProperty("jdbc.url");
                username = props.getProperty("jdbc.username");
                password = props.getProperty("jdbc.password");
                driver = props.getProperty("jdbc.driver");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取数据库连接
     * @return Connection对象
     * @throws SQLException SQL异常
     */
    public static Connection getConnection() throws SQLException {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            throw new SQLException("数据库驱动加载失败", e);
        }
    }
    
    /**
     * 关闭数据库连接
     * @param conn Connection对象
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 关闭Statement
     * @param stmt Statement对象
     */
    public static void closeStatement(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 关闭ResultSet
     * @param rs ResultSet对象
     */
    public static void closeResultSet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 关闭所有资源
     * @param conn Connection对象
     * @param stmt Statement对象
     * @param rs ResultSet对象
     */
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        closeResultSet(rs);
        closeStatement(stmt);
        closeConnection(conn);
    }
    
    /**
     * 执行更新操作（INSERT、UPDATE、DELETE）
     * @param sql SQL语句
     * @param params 参数数组
     * @return 影响的行数
     */
    public static int executeUpdate(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        } finally {
            closeAll(conn, pstmt, null);
        }
    }
    
    /**
     * 执行查询操作
     * @param sql SQL语句
     * @param params 参数数组
     * @return ResultSet对象
     */
    public static ResultSet executeQuery(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            rs = pstmt.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            closeAll(conn, pstmt, rs);
            return null;
        }
    }
} 